#include "apue.h"
#include <sys/wait.h>

void pr_siginfo(siginfo_t *);

int main(void) {
    pid_t pid;
    int status;
    siginfo_t siginfo;

    if ((pid = fork()) < 0)
        err_sys("fork error");
    else if (pid == 0)          /* child */
        exit(7);

    if (waitid(P_PID, pid, &siginfo, WEXITED) < 0)   /* wait for child */
        err_sys("wait error");
    pr_siginfo(&siginfo);

    if ((pid = fork()) < 0)
        err_sys("fork error");
    else if (pid == 0)
        abort();

    if (waitid(P_PID, pid, &siginfo, WEXITED) < 0)
        err_sys("wait error");
    pr_siginfo(&siginfo);


    if ((pid= fork()) < 0)
        err_sys("fork error");
    else if (pid == 0)
        status /= 0;

    if (waitid(P_PID, pid, &siginfo, WEXITED) < 0)
        err_sys("wait error");
    pr_siginfo(&siginfo);

    exit(0);
}


//void pr_exit(int status) {
//    if (WIFEXITED(status))
//        printf("normal termination, exit status = %d\n", WEXITSTATUS(status));
//    else if (WIFSIGNALED(status))
//        printf("abnormal termination, signal number = %d%s\n", 
//                WTERMSIG(status),
//#ifdef WCOREDUMP
//                WCOREDUMP(status) ? " (core file generated)" : "");
//#else
//                "");
//#endif
//
//    else if (WIFSTOPPED(status)) 
//        printf("child stopped, signal number = %d\n", WSTOPSIG(status));
//
//}

void pr_siginfo(siginfo_t * siginfo) {
    if (siginfo->si_code == CLD_EXITED) {
        printf("normal termination, exit status = %d\n", siginfo->si_status);

    } else if (siginfo->si_code == CLD_KILLED || siginfo->si_code == CLD_DUMPED) {
        
        printf("abnormal termination, signal number = %d", siginfo->si_status);
        puts(siginfo->si_code == CLD_DUMPED ? "(core file generated)" : "");

    } else if (siginfo->si_code == CLD_STOPPED) {
        printf("child stopped, signal number = %d\n", siginfo->si_status);
    }
}
